package zhtt;

import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * Created by zhtt on 2017/4/10.
 */
public class JunitTest_group {

    private Session session;

    @Before
    public void setUp(){
        session=HbnUtil.getSession();
    }

    @Test
    public void sql(){
        try{
            session.beginTransaction();
            String sql="select * from zhtt0_student group by age";
            List<Student> list1=session.createSQLQuery(sql).addEntity(Student.class).list();
            System.out.println(list1);

            List<Object> list2=session.createSQLQuery(sql).list();
            System.out.println(list2);

            String sql3="select * from zhtt0_student group by age HAVING  count(age)>?";
            List<Object> list3=session.createSQLQuery(sql3).setInteger(0,1).list();
            System.out.println(list3);
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();;
        }
    }

    @Test
    public void hql(){
        try{
            session.beginTransaction();
            String sql="select age from Student group by age";/** 不能 【select *】 **/
            List<Object> list1=session.createQuery(sql).list();
            System.out.println(list1);

            String sql3="select age from Student group by age HAVING  count(age)>?";/** 不能 【select *】 **/
            List<Object> list3=session.createQuery(sql3).setInteger(0,1).list();
            System.out.println(list3);
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();;
        }
    }

    @Test
    public void qbc(){
        try{
            session.beginTransaction();
            List<Object> list=session.createCriteria(Student.class)
                    .setProjection(Projections.groupProperty("age"))
                    .list();
                System.out.println(list);
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();;
        }
    }
}
